import requests
from lxml import html
from wtforms.ext.appengine import db


def get_data():
    url = 'http://www.stat-nba.com/player/1717.html'
    headers = {
        'User-Agent': 'Mozilla / 5.0(Windows NT 10.0;Win64;x64;rv: 84.0) Gecko / 20100101Firefox / 84.0'
    }
    response = requests.get(url, headers=headers)
    etree = html.etree
    e = etree.HTML(response.text)
    scores = e.xpath('// table[ @ id = "stat_box_avg"] // tr // td[24] / text()')
    backboards = e.xpath('// table[ @ id = "stat_box_avg"] // tr // td[16] / text()')
    assists = e.xpath('// table[ @ id = "stat_box_avg"] // tr // td[19] / text()')
    steal = e.xpath('// table[ @ id = "stat_box_avg"] // tr // td[20] / text()')
    block = e.xpath('//table[ @ id = "stat_box_avg"] // tr // td[21] / text()')
    years = e.xpath('// table[ @ id = "stat_box_avg"] / tbody / tr /td[2]/a/text()')

    del (scores[-1])
    del (backboards[-1])
    del (assists[-1])
    del (steal[-1])
    del (block[-1])

    scores.reverse()
    backboards.reverse()
    assists.reverse()
    steal.reverse()
    block.reverse()
    years.reverse()

    for i in range(0, 15):
        scores[i] = float(scores[i])
        backboards[i] = float(backboards[i])
        assists[i] = float(assists[i])
        steal[i] = float(steal[i])
        block[i] = float(block[i])
    print(scores)
    print(backboards)
    print(assists)
    print(steal)
    print(block)
    print(years)
    return scores, backboards, assists, steal, block, years


def insert_into_mysql(shuju_list):
    name = 'Jordan'
    cursor = db.cursor()
    # SQL 插入语句
    sql = "INSERT INTO avegshow VALUES\
    ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" \
          % (
              name, shuju_list[0], shuju_list[1], shuju_list[2], shuju_list[3], shuju_list[4], shuju_list[5],
              shuju_list[6] \
                  , shuju_list[7], shuju_list[8], shuju_list[9], shuju_list[10], shuju_list[11], shuju_list[12],
              shuju_list[13], shuju_list[14])
    print(sql)
    try:
        # cursor.executemany(sql, usersvalues)
        # 执行sql语句
        cursor.execute(sql)
        # 提交到数据库执行
        db.commit()
    except UnicodeEncodeError:
        # Rollback in case there is any error
        print("error")
    # 关闭数据库连接
    db.close()


if __name__ == '__main__':
    get_data()